package com.guaji.system.NoteAPP

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.guaji.system.NoteAPP.data.Note
import com.guaji.system.NoteAPP.roomsql.AppDatabase
import com.bumptech.glide.Glide
import com.google.android.material.button.MaterialButton
import com.guaji.system.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream

class DetailActivity : AppCompatActivity() {

    private lateinit var noteDatabase: AppDatabase
    private lateinit var note: Note
    private lateinit var titleEditText: EditText
    private lateinit var contentEditText: EditText
    private lateinit var imageView: ImageView
    private lateinit var saveButton: MaterialButton
    private lateinit var cancelButton: MaterialButton
    private var currentImageUri: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detail)

        // 初始化视图
        titleEditText = findViewById(R.id.detail_title_edittext)
        contentEditText = findViewById(R.id.detail_content_edittext)
        imageView = findViewById(R.id.detail_image)
        saveButton = findViewById(R.id.save_note_button)
        cancelButton = findViewById(R.id.delete_note_button)

        // 初始化数据库
        noteDatabase = AppDatabase.getInstance(this)

        // 从Intent中获取笔记ID
        val noteId = intent.getLongExtra("note_id", -1)
        if (noteId == -1L) {
            Toast.makeText(this, "笔记ID无效", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        // 根据笔记ID加载笔记数据
        lifecycleScope.launch(Dispatchers.IO) {
            note = noteDatabase.noteDao().getNoteById(noteId) ?: return@launch

            withContext(Dispatchers.Main) {
                titleEditText.setText(note.title)
                contentEditText.setText(note.content)

                if (note.imageUri?.isNotEmpty() == true) {
                    Log.d("DetailActivity", "加载图片路径: ${note.imageUri}")
                    val imageFile = File(note.imageUri)
                    if (imageFile.exists()) {
                        Glide.with(this@DetailActivity)
                            .load(imageFile)
                            .centerCrop()
                            .into(imageView)
                        imageView.visibility = View.VISIBLE
                    } else {
                        Log.e("DetailActivity", "图片文件不存在: ${note.imageUri}")
                        imageView.visibility = View.GONE
                        Toast.makeText(this@DetailActivity, "图片文件已丢失", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Log.d("DetailActivity", "无图片路径")
                    imageView.visibility = View.GONE
                }
            }
        }

        // 保存按钮点击事件
        saveButton.setOnClickListener {
            val updatedTitle = titleEditText.text.toString().trim()
            val updatedContent = contentEditText.text.toString().trim()

            if (updatedTitle.isNotEmpty()) {
                // 如果有新图片，则使用新路径；否则保留旧路径
                val updatedImageUri = currentImageUri ?: note.imageUri
                Log.d("DetailActivity", "保存的图片路径：$updatedImageUri")

                val updatedNote = Note(
                    id = note.id,
                    title = updatedTitle,
                    content = updatedContent,
                    imageUri = updatedImageUri
                )

                // 执行数据库更新操作
                lifecycleScope.launch(Dispatchers.IO) {
                    noteDatabase.noteDao().updateNote(updatedNote)

                    withContext(Dispatchers.Main) {
                        // 设置结果并返回
                        setResult(RESULT_OK)
                        Toast.makeText(this@DetailActivity, "笔记已保存", Toast.LENGTH_SHORT).show()
                        finish()
                    }
                }
            } else {
                Toast.makeText(this, "标题不能为空", Toast.LENGTH_SHORT).show()
            }
        }

        // 取消/返回按钮点击事件
        cancelButton.setOnClickListener {
            finish() // 直接返回
        }

        // 添加图片按钮点击事件
        findViewById<MaterialButton>(R.id.add_image_button).setOnClickListener {
            selectImage()
        }
    }

    // 图片选择处理
    private val imagePickerLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val data: Intent? = result.data
            val uri: Uri? = data?.data
            uri?.let {
                try {
                    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
                    val cacheDir = externalCacheDir ?: return@registerForActivityResult
                    val fileName = "note_img_${System.currentTimeMillis()}.jpg"
                    val tempFile = File(cacheDir, fileName)
                    val outputStream = FileOutputStream(tempFile)
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream)
                    outputStream.flush()
                    outputStream.close()

                    // 更新当前图片路径
                    currentImageUri = tempFile.absolutePath
                    Log.d("DetailActivity", "新图片路径：$currentImageUri")

                    // 更新图片预览
                    imageView.visibility = View.VISIBLE
                    Glide.with(this@DetailActivity)
                        .load(tempFile)
                        .centerCrop()
                        .into(imageView)
                } catch (e: Exception) {
                    e.printStackTrace()
                    Toast.makeText(this, "图片处理失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun selectImage() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        intent.type = "image/*"
        imagePickerLauncher.launch(intent)
    }
}